﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using System.Deployment;

namespace GetooLibs
{
    public static class Utility
    {


        public static string GetFileHash(string filename)
        {
            byte[] byteHashValue;
            try
            {
                FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                using (fs)
                {
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    byteHashValue = sha1.ComputeHash(fs);

                }
                return BitConverter.ToString(byteHashValue).Replace("-", string.Empty);
            }
            catch (Exception ex)
            {
                return filename + " "+ ex.Message;
                //throw;
            }




        }

        public static void SaveGetooDatabaseFile(string databasePath, GetooDatabaseFile db)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(databasePath, FileMode.OpenOrCreate);
            using (stream)
            {
                formatter.Serialize(stream, db);
            }
        }

        public static GetooDatabaseFile LoadGetooDatabaseFile(string databasePath)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                FileStream stream = new FileStream(databasePath, FileMode.Open);
                using (stream)
                {
                    return (GetooDatabaseFile)formatter.Deserialize(stream);
                }
            }
            catch (Exception)
            {
                return new GetooDatabaseFile();    
                //throw;
            }

            


        }

        public static GetooDatabaseFile LoadGetooDatabaseFile(byte[] databaseBytes) 
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            BinaryWriter writer=new BinaryWriter(stream);

            
            using (stream)
            {
                writer.Write(databaseBytes);
                stream.Position = 0;
                return (GetooDatabaseFile)formatter.Deserialize(stream);
            }

        }


    }
}
